package com.huarui.user.action;

import java.util.UUID;
import java.util.concurrent.TimeoutException;

import javax.servlet.http.HttpServletRequest;

import net.rubyeye.xmemcached.XMemcachedClient;
import net.rubyeye.xmemcached.exception.MemcachedException;

import org.apache.commons.lang.xwork.StringUtils;
import org.apache.log4j.Logger;
import org.ewaf.framework.action.BaseAction;
import org.ewaf.framework.cookie.CookieManager;
import org.ewaf.framework.util.HttpUtil;
import org.ewaf.framework.util.MD5Digester;

import com.huarui.company.model.Company;
import com.huarui.company.service.CompanyService;
import com.huarui.user.error.UserError;
import com.huarui.user.model.CookieConstants;
import com.huarui.user.model.User;
import com.huarui.user.service.UserService;
import com.opensymphony.xwork2.validator.annotations.EmailValidator;
import com.opensymphony.xwork2.validator.annotations.FieldExpressionValidator;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.StringLengthFieldValidator;
import com.opensymphony.xwork2.validator.annotations.Validations;

public class AllRegisterAction extends BaseAction {

	private static final long serialVersionUID = -4977120917664518229L;

	@SuppressWarnings("unused")
	private Logger logger = Logger.getLogger(AllRegisterAction.class);

	private Company company;

	private User user;

	private String verifyCode;

	private String http_email;

	private UserService userService;
    
	private CompanyService companyService;

	private String activeCode;

	private String password2;

	private XMemcachedClient  memcachedClient; 
	
	
	public void setMemcachedClient(XMemcachedClient memcachedClient) {
		this.memcachedClient = memcachedClient;
	}

	public Company getCompany() {
		return company;
	}

	public void setCompany(Company company) {
		this.company = company;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String getVerifyCode() {
		return verifyCode;
	}

	public void setVerifyCode(String verifyCode) {
		this.verifyCode = verifyCode;
	}

	public String getHttp_email() {
		return http_email;
	}

	public void setHttp_email(String http_email) {
		this.http_email = http_email;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public String getActiveCode() {
		return activeCode;
	}

	public void setActiveCode(String activeCode) {
		this.activeCode = activeCode;
	}

	public String getPassword2() {
		return password2;
	}

	public void setPassword2(String password2) {
		this.password2 = password2;
	}
	public CompanyService getCompanyService() {
		return companyService;
	}

	public void setCompanyService(CompanyService companyService) {
		this.companyService = companyService;
	}

	/**
	 * 注册
	 * 
	 * @return
	 */
	@Validations(requiredStrings = {
			@RequiredStringValidator(fieldName = "password2", shortCircuit = true, key = "user.password2.required"),
			@RequiredStringValidator(fieldName = "user.email", shortCircuit = true, key = "user.email.required"),
			@RequiredStringValidator(fieldName = "company.name", shortCircuit = false, key = "company.name.required"),
			@RequiredStringValidator(fieldName = "user.password", shortCircuit = true, key = "user.password.required"),
			@RequiredStringValidator(fieldName = "user.name", shortCircuit = true, key = "user.name.required") }, emails = { @EmailValidator(fieldName = "user.email", shortCircuit = true, key = "user.email.format.error") }, stringLengthFields = {
			@StringLengthFieldValidator(fieldName = "user.name", maxLength = "20", shortCircuit = true, key = "user.name.length.error"),
			@StringLengthFieldValidator(fieldName = "user.password", minLength = "6", shortCircuit = true, key = "user.password.length.minerror"),
			@StringLengthFieldValidator(fieldName = "password2", minLength = "6", shortCircuit = true, key = "user.password.length.minerror") }, fieldExpressions = { @FieldExpressionValidator(fieldName = "password2", expression = "password2==user.password", shortCircuit = true, key = "user.password2.same.error") })
	public String submit() {

		HttpServletRequest request = HttpUtil.getRequest();

		CookieManager cookie = new CookieManager(request);

		user.setPassword(MD5Digester.digest(user.getPassword()));

		String code = cookie.getValue(CookieConstants.COOKIE_CODE, "code");

		String checkCode="";
		try {
			checkCode = memcachedClient.get(code);
			
			memcachedClient.delete(code);
		} catch (TimeoutException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (MemcachedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		if (!StringUtils.trim(verifyCode).equalsIgnoreCase(checkCode)) {

			this.addFieldError("verifyCode", UserError.VERIFYCODE_WRONG
					.getChError());

			return INPUT;
		}

		// 验证成功后删除关于验证码的cookie
		cookie.removeCookie(httpServletResponse, null,
				CookieConstants.Cookie_PATH, CookieConstants.COOKIE_CODE);

		User u = userService.getUserByEmail(user.getEmail());

		if (u != null) {

			this.addFieldError("user.email", UserError.DUPLICATED_EMAIL
					.getChError());

			return INPUT;
		}

		activeCode = UUID.randomUUID().toString();

		user.setActivateCode(activeCode);

		try {

			companyService.createUserAndCompany(user, company);

		} catch (Exception e) {
             e.printStackTrace(); 
			throw new RuntimeException(e.getMessage());
		}
		companyService.sendActiveEmail(user,company);

		http_email = "http://mail."
				+ user.getEmail().substring(user.getEmail().indexOf("@") + 1);

		if (http_email.equals("http://mail.gmail.com")) {

			http_email = "http://mail.google.com";

		}

		return SUCCESS;
	}

	
	/**
	 * 激活用户和公司
	 * 
	 * @return
	 */

	public String activeUserAndCompanySubmit() {

		HttpServletRequest request = HttpUtil.getRequest();

		String activeCode = request.getParameter("activeCode");

		user = userService.getByActiveCode(activeCode);
		
		if(user==null){
			
			throw new RuntimeException(UserError.ACTIVE_FAILTURE.getChError());
			
		}
		
        company=(Company)companyService.getById(user.getCompanyId());
		
	 try{	
		 
		 userService.activeUser(user);
		
	 }catch (Exception e) {
		 
		 logger.debug(e.getMessage());
		 throw new RuntimeException(UserError.ACTIVE_FAILTURE.getChError());

	}
		return SUCCESS;

	}
}
